import { useUserStore } from '@/stores'

/**
 * 检查当前用户是否有指定权限
 * @param {String} permission 权限编码
 * @returns {Boolean}
 */
export function hasPermission(permission) {
  const userStore = useUserStore()
  const permissions = userStore.permissions || []

  if (!permissions || permissions.length === 0) {
    // 尝试从localStorage恢复权限
    try {
      const savedPermissions = localStorage.getItem('user_permissions')
      if (savedPermissions) {
        const restoredPermissions = JSON.parse(savedPermissions)
        if (restoredPermissions.includes('*:*:*')) {
          return true
        }
        if (restoredPermissions.includes(permission)) {
          return true
        }
      }
    } catch (e) {
      console.error('权限恢复失败:', e)
    }
    return false
  }

  // 超级管理员拥有所有权限
  if (permissions.includes('*:*:*')) {
    return true
  }

  // 精确匹配权限编码
  const result = permissions.includes(permission)

  // 如果精确匹配失败，尝试检查是否有该权限的父级权限
  if (!result && permission.includes(':')) {
    const parts = permission.split(':')
    if (parts.length >= 2) {
      const parentPermission = parts[0] + ':*:*'
      const modulePermission = parts[0] + ':' + parts[1] + ':*'

      const hasParentPerm = permissions.includes(parentPermission)
      const hasModulePerm = permissions.includes(modulePermission)

      if (hasParentPerm || hasModulePerm) {
        return true
      }
    }
  }

  return result
}

/**
 * 权限指令
 */
export const permission = {
  mounted(el, binding) {
    const { value } = binding
    if (value) {
      const hasAuth = hasPermission(value)
      if (!hasAuth) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  },

  // 添加更新钩子，确保在权限变更时重新检查
  updated(el, binding) {
    const { value } = binding
    if (value) {
      const hasAuth = hasPermission(value)
      if (!hasAuth && el.parentNode) {
        el.parentNode.removeChild(el)
      }
    }
  }
}

/**
 * 权限按钮组件属性
 */
export const permissionButton = {
  props: {
    permission: {
      type: String,
      default: ''
    }
  },
  computed: {
    hasPermission() {
      return hasPermission(this.permission)
    }
  }
}
